import React from 'react';
import { urlMd, for_obj, is_empty, hand_edit, HandBase, obj_str, ck_empty, obj_empty } from '../../nui';
import { loc } from '../../local';

const QcHand = ({ hreturn, cur, bom, cfg, main, mod, labedit, labadd, info=null }) => {
    const getLst = () => {
        if (obj_empty(cfg)) {
            return null;
        }

        const lst = [];

        for_obj(cfg, (k, v) => {
            if (k === "pos") {
                return;
            }

            lst.push({sn: k, name: v, ck: ck_empty})
        });

        return lst;
    };

    const get_data = (value) => {
        const lst = getLst();

        return lst.map(d => {
            const sn = d.sn;
            return {k: sn, v: obj_str(value, sn)};
        });
    };

    const hadd = (value, umd) => {
        umd.startWait();

        const data = get_data(value);
        if (is_empty(main)) {
            data.push({k: "pos", v: "1"});
        }
        else {
            const d = main[main.length - 1];
            let pos = parseInt(d.pos, 10) + 1;
            if (isNaN(pos)) {
                pos = parseInt(d.index, 10) + 1;
                if (isNaN(pos)) {
                    pos = 100;
                }
            }

            data.push({k: "pos", v: "" + pos});
        }

        const cmd = {
            a: [{
                u: bom.uid,
                n: mod,
                v: [data]
            }]
        };

        urlMd(null, cmd,
            r => {
                umd.endWait();
                hreturn();
            },
            e => umd.setWrong(loc("tjsb")));
    };

    const hedit = (value, umd) => {
        const data = get_data(value);
        hand_edit(cur, data, umd, hreturn);
    };

    const getTitle = () => {
        if (obj_empty(cur)) {
            return `${bom.sn} ( ${bom.name} ) >> ${labadd}`;
        }

        return `${cur.sn} ( ${cur.name} ) >> ${labedit}`;
    };

    const hinit = () => {
        if (obj_empty(cur)) {
            return null;
        }

        return cur;
    };

    return <HandBase init={hinit()} hedit={hedit} hadd={hadd} cur={cur} lst={getLst()} hreturn={hreturn} title={getTitle()} info={info}/>;
};

export {QcHand};
